import { ref,computed,  onMounted } from 'vue';
import type { Ref } from 'vue';
import type {hooksParam} from '.'
import { getPx } from '../../../libs/utils/_utils';
import { sleep, } from '../../../libs/utils';

 const useChat = (option: Ref<hooksParam>, emit: ReturnType<typeof defineEmits>,safeAreaBottom:Ref<number>,scrollToBottom:Function) => {
	// 键盘高度
	const keyboardHeight = ref(0);
	// 键盘高度是否未改变，此时占位高度变化不需要动画效果
	const isKeyboardHeightChanged = ref(false);

	const finalChatRecordMoreOffset = computed(() => {
		return getPx(option.value.chatRecordMoreOffset);
	});
	const finalChatAdjustPositionOffset = computed(() => {
		return getPx(option.value.chatAdjustPositionOffset);
	})


	// 最终的聊天记录模式中底部安全区域的高度，如果开启了底部安全区域并且键盘未弹出，则添加底部区域高度
	const chatRecordModeSafeAreaBottom = computed(() => {
		return option.value.safeAreaInsetBottom && !keyboardHeight.value ? safeAreaBottom.value : 0;
	});

	// 手动触发滚动到顶部加载更多，聊天记录模式时有效
	const doChatRecordLoadMore = () => {
		option.value.useChatRecordMode && emit('scrolltolower', 'click');
	};
	// 处理键盘高度变化
	const handleKeyboardHeightChange = async (res:UniNamespace.OnKeyboardHeightChangeResult) => {
		emit('keyboardHeightChange', res);
		if (option.value.autoAdjustPositionWhenChat) {
			isKeyboardHeightChanged.value = true;
			keyboardHeight.value = res.height > 0 ? res.height + finalChatAdjustPositionOffset.value : res.height;
		}
		if (option.value.autoToBottomWhenChat && keyboardHeight.value > 0) {
			await sleep(100);
			scrollToBottom(false);
			await sleep(100);
			scrollToBottom(false);
		}
	};

	onMounted(() => {
		// 监听键盘高度变化（H5、百度小程序、抖音小程序、飞书小程序不支持）
		// #ifndef H5 || MP-BAIDU || MP-TOUTIAO
		if (option.value.useChatRecordMode) {
			uni.onKeyboardHeightChange(handleKeyboardHeightChange);
		}
		// #endif
	});

	return {
		finalChatRecordMoreOffset,
		finalChatAdjustPositionOffset,
		chatRecordModeSafeAreaBottom,
		doChatRecordLoadMore,
		handleKeyboardHeightChange
	};
};

export default useChat